<?php
/**
 * Created by PhpStorm.
 * User: elliot
 * Date: 2017/4/12
 * Time: 16:22
 */
namespace app\service;

class MessagePush{

    protected $appid;
    protected $secret;
    protected $accessToken;

    public function __construct()
    {
        $this -> appid ="wx83a8ac5e75677d65";
        $this -> secret = "6d2f826f395b3918c33036ce38cec675";
        $this -> accessToken = $this -> getToken("wx83a8ac5e75677d65", "6d2f826f395b3918c33036ce38cec675");
    }

    /**
     * post请求
     * @param string $url
     * @param string $param
     * @return bool|mixed
     */
    public function request_post($url = '', $param = ''){
        if(empty($url) || empty($param)){
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }

    /**
     * get请求
     * @param string $url
     * @return bool|mixed
     */
    public function request_get($url = ''){
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    /**
     * @param $appid
     * @param $appSecret
     * @return mixed
     */
    public function getToken($appid, $appSecret){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=". $appid . "&secret=" . $appSecret;
        $token = $this->request_get($url);
        $token = json_decode(stripslashes($token));
        $arr = json_decode(json_encode($token), true);
        $access_token = $arr['access_token'];
        return $access_token;
    }

    /**
     * 消息推送
     * @param $touser
     * @param $template_id
     * @param string $url
     * @param $data
     * @param string $topcolor
     * @return bool
     */
    public function doSend($touser, $template_id, $url='', $data, $topcolor = '#7B68EE'){
        $template = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'topcolor' => $topcolor,
            'data' => $data
        );
        $json_template = json_encode($template);

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $this->accessToken;
        $dataRes = $this->request_post($url, urldecode($json_template));
        if ($dataRes['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }
}